/// pages/detail/detail.js
const WxParse = require('../../wxParse/wxParse.js');
var guige = false, goodId;
const getToken = require('../../utils/get_token.js');
const checkToken = require('../../utils/check_token.js');
const mulit = require('../../utils/m.js');
let cookie, token;
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    goodShopsn(that);
  } else {
    let tokens = await getToken.getToken();
    goodShopsn(that);
  }
}
const goodShopsn = (that) => {//标签
  let params = ['shop/goods/goods', {"goodId": goodId}]
  getToken.getData(function (res) {
    console.log(res.data);
    res.data.price = res.data.price.toFixed(2);
    res.data.yunfei = res.data.yunfei.toFixed(2);
    res.data.produsts = res.data.produsts || '';
    var imgs = [];
    var Urls = res.data.goodsImage;
    var re = /\/hexishop/g;
    var article = res.data.introduction.replace(re, 'http://image.globalhexi.com');;
    WxParse.wxParse('article', 'html', article, that, 0);
    for (let i = 0; i < Urls.length; i++)//大图
    {
      var Url = `https://www.globalhexi.com/${Urls[i].path}/big/${Urls[i].id}.jpg`;
      imgs.push(Url);
		}
		res.data.shop_logo='http://www.globalhexi.com/'+res.data.shop_logo;
    that.setData({
      s: res.data,
      imgUrls: imgs,
      p: res.data.produsts,
      sc: res.data.specification,
      sv: res.data.specificationValue,
      price: res.data.price,
      store: res.data.store,
      productId: res.data.productid,
      isMarketable: res.data.isMarketable,
      hidden: true
    })
    var olist = [];
    if (that.data.sc.length > 0) {
      guige = true;
      that.setData({
        bool: false
      })
      for (var k = 0; k < that.data.sc.length; k++)//展示
      {
        olist[k] = { name: that.data.sc[k].name, ul: [] };
        for (var t = 0; t < that.data.sv.length; t++) {
          for (var s = 0; s < that.data.sc[k].specificationValueList.length; s++) {
            if (that.data.sv[t].id == that.data.sc[k].specificationValueList[s].id) {
              olist[k].ul.push({ id: that.data.sv[t].id, name: that.data.sv[t].name, disable: null, trueS: false, row: k, current: false })
            }
          }
        }
      }
    } else {
      guige = false;
    }
    that.setData({
      clist: olist
    })
  }, ...params)
}


var domo = function (that,p){
	var arrObj=[];
	var sarr=[];
	if (p.length > 0) {
		for (var i = 0; i < p.length; i++) {
			var oProduct = {};
			oProduct.id = p[i].id;
			oProduct.price = p[i].price;
			oProduct.store = p[i].store;
			oProduct.arr = [];
			for (var j = 0; j < p[i].specificationValueList.length; j++) {
				oProduct.arr.push(p[i].specificationValueList[j].id);
			}
			arrObj.push(oProduct);
		}
	
		for (var j = 0; j < that.data.clist.length; j++)//确定
		{
			for (var k = 0; k < that.data.clist[j].ul.length; k++) {
				if (that.data.clist[j].ul[k].current == true) {
					sarr.push(that.data.clist[j].ul[k].id);
				}
			}
		}
		var tarr=[];
		for (let i = 0; i < arrObj.length;i++)//比较
		{
			for (let j = 0; j < arrObj[i].arr.length;j++)
			{ 
				for(let k=0;k<sarr.length;k++)
				{
					if (arrObj[i].arr[j] == sarr[k])
					{
						tarr.push(arrObj[i].arr[j])
						if (tarr.length == arrObj[i].arr.length)
						{
							if (JSON.stringify(arrObj[i].arr) == JSON.stringify(tarr)) {
								return arrObj[i].id;
							}
						}
					}
				}
			}
			tarr = [];
		}
	}
}
Page({
  data: {
		winHeight:0,
		indicatorDots: true,
		indicatorC: "#fff",
		indicatorAC: "red",
		autoplay: false,
		interval: 5000,
		duration: 500,
		circular: true,
		imgUrls: [],
    
		s:{},
    p:[],
    sc:{},
    sv:{},
    clist:[],
    memberId:'',
		price:'',
		store:'',
		amount:1,
		productId:'',
		isScroll:true,
		isMarketable:true,
		scrollTop:0,
		open:false,
		bool:true,
		boolT: true,
		hidden:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		 goodId = options.id;
     var that = this;
    this.data.memberId = wx.getStorageSync('memberId');
    cookie = wx.getStorageSync('cookie') || '';
    token = wx.getStorageSync('token') || '';
    ckToken(that);
		//  高度自适应
		wx.getSystemInfo({
			success: function (res) {
				var clientHeight = res.windowHeight,
					clientWidth = res.windowWidth,
					rpxR = 750 / clientWidth;
				var calc = clientHeight * rpxR;
				that.setData({
					winHeight: calc
				});
			}
		});
		
  },
	onShow: function () {
    this.setData({
      open: false,
    })
  },
	closeD:function(e){
		this.setData({
			open: false,
			isScroll: true,
			scrollTop: 0
		})
	},

  selectd:function(e){//规格选择
		var that=this;
		var index=0;
		var thisId = e.target.dataset.id;
		var arrId=[];
		var disable = e.target.dataset.disable;
		var rows = e.target.dataset.row;
		var current = e.target.dataset.current;
		that.setData({
			bool: false
		})
		if (current)//取消所有选择
	 {
		 for (var j = 0; j < that.data.clist.length; j++) {
				 for (var k = 0; k < that.data.clist[j].ul.length; k++) {
					 that.data.clist[j].ul[k].current = false;
					 that.data.clist[j].ul[k].disable = null;
				 }
		 } 
	 }else{
		 for (var j = 0; j < that.data.clist.length; j++) {//取消同行
			 if (j == rows){
				 for (var k = 0; k < that.data.clist[j].ul.length;k++)
				 {
					 that.data.clist[j].ul[k].current=false;
				 }
			 }
		 }
		 for (var j = 0; j < that.data.clist.length; j++) {//取消被限制的
				 for (var k = 0; k < that.data.clist[j].ul.length; k++) {
					 if (rows == that.data.clist[j].ul[k].disable){
						 that.data.clist[j].ul[k].disable = null;
					 }
				 }
		 }
		 for (var j = 0; j < that.data.clist.length; j++) {//增加active
			 for (var k = 0; k < that.data.clist[j].ul.length; k++) {
				 if (thisId== that.data.clist[j].ul[k].id) {
					 that.data.clist[j].ul[k].current = true;
				 }
			 }
		 }
		 for (var i = 0; i < that.data.p.length; i++)//通过id找出与这个型号所有匹配的类型
		 {
			 for (var j = 0; j < that.data.p[i].specificationValueList.length; j++) {
				 if (thisId == that.data.p[i].specificationValueList[j].id) {
					 for (var t = 0; t < that.data.p[i].specificationValueList.length; t++) {
						 arrId.push(that.data.p[i].specificationValueList[t].id);
					 }
				 }
			 }
		 }
		 for (var i = 0; i < arrId.length; i++)//给匹配的li加上trueclass名称
		 {
			 for (var j = 0; j < that.data.clist.length; j++) {
				 for (var k = 0; k < that.data.clist[j].ul.length; k++) {
					 if (arrId[i] == that.data.clist[j].ul[k].id) {
						 that.data.clist[j].ul[k].trueS = true;
					 }
				 }
			 }
		 }
		 for (var j = 0; j < that.data.clist.length; j++) {
			 for (var k = 0; k < that.data.clist[j].ul.length; k++) {
				 if (disable == rows) {
					 //增加点击
					 that.data.clist[j].ul[k].disable = null;
				 }
				 if (rows != that.data.clist[j].ul[k].row && that.data.clist[j].ul[k].trueS == false) {
					 //取消点击
					 that.data.clist[j].ul[k].disable = rows;
				 }
			 }
		 }
		 for (var j = 0; j < that.data.clist.length; j++)//回复到默认值
		  {
			 for (var k = 0; k < that.data.clist[j].ul.length; k++) {
				 that.data.clist[j].ul[k].trueS = false;
			 }
		 }
		 for (var j = 0; j < that.data.clist.length; j++)//确定
		 {
			 for (var k = 0; k < that.data.clist[j].ul.length; k++) 
			 {
				 if (that.data.clist[j].ul[k].current==true)
				 {
					 index++;
					 if (index == that.data.clist.length)
					 {
						var productId=domo(that, that.data.p);
						console.log(productId)
						for(var z=0;z<that.data.p.length;z++)
						{
							if (productId == that.data.p[z].id)
							{
								that.setData({
									price: that.data.p[z].price.toFixed(2),
									bool:true,
									store: that.data.p[z].store
								})
							}
						}
					 }
				 }
			 }
		 }
	 } 
		that.setData({
			clist: that.data.clist
		})
  },
  buyTh: function (e) {
    var that = this;
    var memberId = this.data.memberId;
    if (that.data.boolT) {
      that.data.boolT = false;
      if (memberId == '') {//是否登录
        wx.navigateTo({
          url: '../login/login?id=5',
          success: function () {
          }
        })
      } else {
        this.setData({
          open: true,
          isScroll: false,
          scrollTop: 0
        })
      }
      setTimeout(function () {
        that.data.boolT = true;
      }, 500) 
    }
  },
  sure:function(e){//购买
		let that=this;
    let memberId = this.data.memberId;
		if (that.data.boolT) {
			that.data.boolT = false;
		   //下一步是否有地址
      let params = [ 'common', 'common/receiver/list', '{"id":"' + memberId + '"}']
      getToken.getData(function (res) {
        let lists = res.data.lists
        if (lists.length > 0)//有地址
        {
          if (guige) {
            that.data.productId = domo(that, that.data.p);
            if (that.data.productId == undefined) {
            } else {
              wx.setStorageSync('pood', { productId: that.data.productId, amount: that.data.amount, price: that.data.price, limit: that.data.store, classify: 0 });
              wx.navigateTo({
                url: '../confirm_order/confirm_order?id=' + goodId,
                success: function () {
                  setTimeout(function () {
                    that.data.boolT = true;
                  }, 500)
                }
              })
            }
          } else {//无规格
            wx.setStorageSync('pood', { productId: that.data.productId, amount: that.data.amount, price: that.data.price, limit: that.data.store, classify: 0 });
            wx.navigateTo({
              url: '../confirm_order/confirm_order?id=' + goodId,
              success: function () {
                setTimeout(function () {
                  that.data.boolT = true;
                }, 500)
              }
            })
          }
        } else {
          wx.navigateTo({
            url: '../new_address/new_address',
            success: function () {
              setTimeout(function () {
                that.data.boolT = true;
              }, 500)
            }
          })
        }
      }, ...params)
		}	
  },
	jian: function (e) {
		var that = this;
		if (that.data.amount > 1) {
			that.setData({
				amount: that.data.amount - 1
			})
		}
	},
	jia: function (e) {
		var that = this;
		if (that.data.store > that.data.amount){
			that.setData({
				amount: that.data.amount + 1
			})
		}
	},
  /**
   * 用户点击右上角分享
   */
	onShareAppMessage: function (res) {
    var that = this;
		if (res.from === 'button') {
			// 来自页面内转发按钮
			console.log(res.target)
		}
		return {
      title: that.data.s.name,
			path: '/pages/detail/detail?id=' + goodId,
			success: function (res) {
				// 转发成功
			},
			fail: function (res) {
				// 转发失败
			}
		}
	}
})